package fileapi

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"iot-base/common/webapi"
	"os"
	"path/filepath"
	"strings"
)

func downFile(fileName string, c *gin.Context) {
	fileTmp, errByOpenFile := os.Open(fileName)
	if fileTmp != nil {
		defer fileTmp.Close()
	}
	if errByOpenFile != nil {

		webapi.SendError(errByOpenFile.Error()+" filename:"+fileName, webapi.DBError, c)
		return
	}
	c.Header("Content-Type", "application/octet-stream")
	//强制浏览器下载

	//浏览器下载或预览
	//c.Header("Content-Disposition", "inline;filename="+fileName)
	c.Header("Content-Transfer-Encoding", "binary")
	c.Header("Cache-Control", "no-cache")

	c.File(fileName)
}

func initLoadDownAPI(r *gin.RouterGroup) {
	fr := r.Group("/file/")
	{
		fr.GET(":filename", func(c *gin.Context) {
			fileName := c.Param("filename")
			if len(fileName) > 0 {
				dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
				dir = dir + "/files/"
				c.Header("Content-Disposition", "attachment; filename="+fileName)
				downFile(dir+fileName, c)
			} else {
				webapi.SendError("文件名为空", webapi.ParamsError, c)
				return
			}
		})

	}
	fmt.Println("^^^^^^^^^^^^^^^^^^^picinit----------------")
	pr := r.Group("/pic/")
	{
		pr.GET(":filename", func(c *gin.Context) {
			fileName := c.Param("filename")
			parts := strings.Split(fileName, "@")
			if len(parts) == 2 {
				//tfilename := parts[1]
				dir := strings.ReplaceAll(parts[1], "-", "/")
				tfilename := "/home/linaro/work/pic/" + dir + "/" + parts[0]
				c.Header("Content-Disposition", "inline;filename="+fileName+".jpg")
				downFile(tfilename, c)

			} else {
				webapi.SendError("文件名不合法", webapi.ParamsError, c)
			}

		})
	}
}
